# 定义一棵树节点类
class TreeNode:
    def __init__(self, value):
        self.value = value
        self.children = []

    def add_child(self, node):
        self.children.append(node)


class TreeNodeIterator:

    def __init__(self, root):
        if root:
            self.stack = [root]
        else:
            self.stack = []

    def __iter__(self):
        return self

    def __next__(self):
        if self.stack is None:
            return "还没有构建树，请先构建树"

        else:
            node = None
            # 弹出当前节点
            if len(self.stack) > 0:
                node = self.stack.pop()
            if (
                node is not None
                and node.children is not None
                and len(node.children) > 0
            ):
                # 将子节点逆序加入栈（保证前序遍历顺序）
                for child in reversed(node.children):
                    self.stack.append(child)

            return node.value


# 构建示例树
#        A
#       / \
#      B   C
#     / \
#    D   E

a = TreeNode("A")
b = TreeNode("B")
c = TreeNode("C")
d = TreeNode("D")
e = TreeNode("E")

a.add_child(b)
a.add_child(c)

b.add_child(d)
b.add_child(e)

try:
    for node in TreeNodeIterator(a):
        print("遍历的顺序是:", node)
except Exception as e:
    print(e)
